#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

#define my_size 1024
#define max_argv 64
#define SEP " "

char *argv[max_argv];
char pwd[my_size];
char env[my_size];
int lastcode=0;

const char* HostName()//主机名
{
  char* hostname = getenv("HOSTNAME");
  if(hostname)
  {
    return hostname;
  }
  return "None";
}

const char* UserName()//用户名
{

  char* hostname = getenv("USER");
  if(hostname)
  {
    return hostname;
  }
  return "None";
}

const char* CurrentWorkDir()//工作目录
{
  char* hostname = getenv("PWD");
  if(hostname)
  {
    return hostname;  
  }
  return "None";
}

char* Home()
{
  return getenv("HOME");
}

int Interactive(char out[],int size)//录取
{
  printf("[%s@%s %s]",UserName(),HostName(),CurrentWorkDir());
  fgets(out,size,stdin);
  out[strlen(out)-1]=0;
  return strlen(out);
}

void Split(char in[])//切割
{
  int i=0;
  argv[i++]=strtok(in,SEP);
  while(argv[i++]=strtok(NULL,SEP))
  {
    ;
  }
}

int BulidinCmd()
{
  int ret=0;
  if(strcmp("cd",argv[0])==0)//检测是否是内建命令
  {
    ret=1;
    char* target=argv[1];
    if(!target)
    {
      target=Home();
    }
    chdir(target);
    char temp[my_size];
    getcwd(temp,1024);
    snprintf(pwd,my_size,"PWD=%s",temp);
    putenv(pwd);//获取环境变量
  }
  else if(strcmp("export",argv[0])==0)
  {
    ret=1;
    if(argv[1])
    {
      strcpy(env,argv[1]);
      putenv(env);
    }
  }
  else if(strcmp("echo",argv[0])==0)
  {
    ret=1;
    if(argv[1]==NULL)
    {
      printf("\n");
      exit(1);
    }
    if(argv[1][0]== '$')
    {
      if(argv[1][1]=='?')
      {
        printf("%d\n",lastcode);
        lastcode=0;
      }
      else
      {
        if(argv[1]+1)
        {
          printf("%s\n",getenv(argv[1]+1));        
        }
      }
    }
    else
    {
      printf("%s\n",argv[1]);
    }
  }
  return ret;
}

void Execute()//执行
{
  pid_t id=fork();
  if(id==0)
  {
    execvp(argv[0],argv);
    exit(1);
  }
  int status=0;
  pid_t rid=waitpid(id,&status,0);
  if(rid==id)
  {
    lastcode=WEXITSTATUS(status);
  }
}

int main()
{
  while(1)
  {
    char commandline[my_size];
    int n=Interactive(commandline,my_size);//打印命令提示符，获取用户输入命令
    if(!n)//处理空串
    {
      continue;
    }
    Split(commandline);//对命令进行切割
    n=BulidinCmd();//处理内建命令
    if(n)
    {
      continue;
    }
    Execute();//执行命令
  }
  return 0;
}
